<%--
  Created by IntelliJ IDEA.
  User: admin
  Date: 2018-12-29
  Time: 21:11
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>角色管理</title>
    <jsp:include page="${pageContext.request.contextPath}/common/common.jsp"/>
</head>
<style>
    .modal-dialog{
        width:400px;
    }
    .form-group label{
        padding:5px 0;
    }
    .margin{
        margin-top:10px;
    }
</style>
<body>
<%--角色信息列表--%>
<div class="panel panel-default">
    <div class="panel-heading">
        <h3 class="panel-title">角色管理</h3>
    </div>
    <div class="panel-body">
        <div class="row">
            <div class="col-sm-6">
                <button class="btn btn-primary" onclick="toAdd()"><span class="glyphicon glyphicon-plus"></span>&nbsp;&nbsp;增加</button>
                <button class="btn btn-primary" onclick="toDel()"><span class="glyphicon glyphicon-trash"></span>&nbsp;&nbsp;删除</button>
            </div>
            <div class="col-sm-6">
                <form  class="form-inline pull-right">
                    <input id="roleName" type="text" class="form-control">
                    <button class="btn btn-primary" type="button" onclick="search()"><span class="glyphicon glyphicon-search"></span>&nbsp;&nbsp;搜索</button>
                </form>
            </div>
        </div>
        <div class="row">
            <div class="col-sm-12">
                <table id="roletb"></table>
            </div>
        </div>
    </div>
</div>
<!-- add Modal -->
<div class="modal fade" id="addModal">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="modelTitleId">添加角色</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal" id="addform" method="post" role="form">
                    <input type="hidden" name="pn"/>
                    <div class="form-group margin">
                        <label class="col-sm-3 text-right">角色:</label>
                        <div class="col-sm-7">
                            <input type="text" name="rname" class="form-control"/>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="doAdd()">保存</button>
            </div>
        </div>
    </div>
</div>
<!-- update Modal -->
<div class="modal fade" id="upModal">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="modelTitleId2">修改角色</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal" id="upform" method="post" role="form">
                    <input type="hidden" name="pn"/>
                    <input type="hidden" name="id"/>
                    <div class="form-group margin">
                        <label class="col-sm-3 text-right">角色:</label>
                        <div class="col-sm-7">
                            <input type="text" name="rname" class="form-control"/>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="doUpdate()">保存</button>
            </div>
        </div>
    </div>
</div>
<%--分配权限--%>
<div class="modal fade" id="perModal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title">分配权限</h4>
            </div>
            <div class="modal-body">
                <div id="searchTree"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="doPer()">分配</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
<script>
    var rid
    function toPer(id){
        rid=id
        var a=0;
        $("#perModal").modal("show");
        $("#perModal").on("shown.bs.modal",function(){
            if(++a==1){
                $.post("${pageContext.request.contextPath}/role/toPer",{"rId":id},function(data){
                    alert(data)
                    $("#searchTree").treeview({
                        data: data,
                        showCheckbox: true,
                        onNodeChecked: nodeChecked,
                        onNodeUnchecked: nodeUnchecked
                    });
                });
            }
        });
    }
    function doPer(){
        var pmId="";
        //1.拿到所选中的权限
        var cks=$("#searchTree").treeview("getChecked");
        $.each(cks,function(i,n){// i 索引 m 节点
            //2.
            pmId+=n.id+"-";
        })
        $.post("${pageContext.request.contextPath}/rolePer/grantPer",{"rId":rid,"pmId":pmId},function(data){

            if(data.msg=="1"){
                //关闭对话框
                $("#perModal").modal("hide");
                //友好提示
                swal("提示信息","分配成功！","success");
            }else{
                //友好提示
                swal("提示信息","分配失败！","success");
            }

        })
    }
    function toAdd(){
        $("#addform [name='rname']").val("");
        $("#addModal").modal("show");
        //在modal隐藏时移除校验重新添加校验
        $("#addModal").on("hidden.bs.modal",function(e){
            //移除上次的校验配置
            $("#addform").data("bootstrapValidator").destroy();
            $("#addform").data("bootstrapValidator",null);
            //重新添加校验
            formValidator();
        })
    }
    function doAdd(){
        //启用校验
        $("#addform").data('bootstrapValidator').validate();
        //验证是否通过true/false
        var flag=$("#addform").data("bootstrapValidator").isValid();
        //判断验证是否通过
        if(flag){
            //绑定当前页开始
            var options=$("#roletb").bootstrapTable("getOptions");
            //得到当前页
            var pn=options.pageNumber;
            $("#addform [name='pn']").val(pn);
            //序列化表单
            var formStr=$("#addform").serialize();
            //处理表单控件的中文乱码
            params=decodeURIComponent(formStr,true);
            //send ajax
            $.ajax({
                "url":"${pageContext.request.contextPath}/role/add",
                "type":"post",
                "data":params,
                success:function(data){
                    //关闭对话框
                    $("#addModal").modal('hide');
                    //重新加载表格
                    $("#roletb").bootstrapTable('load',data);
                    //提示增加成功
                    swal("提示信息","添加成功！","success");
                }
            })
        }
        }
    function doUpdate(){
        //序列化表单
        var formStr=$("#upform").serialize();
        params=decodeURIComponent(formStr,true);
        alert(params);
        $.ajax({
            "url":"${pageContext.request.contextPath }/role/update",
            "type":'post',
            "data":params,
            success:function(data){
                //关闭对话框
                $("#upModal").modal("hide");
                //重新加载表格
                $("#roletb").bootstrapTable("load",data);
                //友好提示
                swal("提示信息","修改成功！","success");

            }
        })

    }
    function toDel(){
        var ids="";
        //得到要删除的行
        //返回所选的行，当没有选择行时返回一个空数组
        var rows=$("#roletb").bootstrapTable("getSelections");
        if(rows==0){
            swal("提示信息","请选择要删除的数据！","error");
        }else{
            $.each(rows,function(index,row){
                ids+=row.id+"-";
            });
            swal({
                title:"您确定要删除这条信息吗",
                text:"删除后无法恢复，请谨慎操作！",
                type:"warning",
                showCancelButton:true,
                confirmButtonColor:"#DD6B55",
                confirmButtonText:"删除",
                closeOnConfirm:false
            },function(){
                //得到当前页
                //绑定当前页开始
                var options=$("#roletb").bootstrapTable("getOptions");
                var roleName=$("#roleName").val();
                //得到当前页
                var pn=options.pageNumber;
                $.post("/role/del",{"ids":ids,"pn":pn,"rname":roleName},function(data){
                    //友好的提示
                    swal("删除成功！","你已经永久删除这条信息。","success");
                    //刷新表格
                    $("#roletb").bootstrapTable("load",data);
                })
            });
        }
    }
    function search(){
        $("#roletb").bootstrapTable('destroy');  // 销毁原表格
        table(); //初始化表格
        //返回表格的option
        var option=$("#roletb").bootstrapTable("getOptions");
        var limit=option.pageSize;
        var offset=(option.pageNumber-1)*limit;
        var roleName=$("#roleName").val();
        $.post("${pageContext.request.contextPath}/role/querySearch",{"rname":roleName,"limit":limit,"offset":offset},function(data){
            $("#roletb").bootstrapTable("load",data);
        });
    }
    function formValidator(){
        <!--校验框架-->
        $("#addform").bootstrapValidator({
            message: 'This value is not valid',
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields:{
                rname:{
                    message: 'The name is not valid',
                    validators:{
                        notEmpty:{//检测非空，radio也可用
                            message:'文本框必须输入'
                        },
                        remote: {//将内容发送至指定页面验证，返回验证结果，查询用户名是否存在
                            url: '/role/checkName',//验证地址
                            type:'post',
                            delay: 1000,//设置2秒发送一次ajax
                            message: '角色名已经存在',
                        }
                    }
                }
            }
        });
    }
    function table(){
        $("#roletb").bootstrapTable({
            url:"${pageContext.request.contextPath}/role/querySearch",
            contentType:"application/x-www-form-urlencoded",
            method:"post",
            height:400,
            //每页显示的条数
            pageSize:2,
            //可供选择的页面数据条数
            pageList:[2,4,8,16],
            //首页页码
            pageNumber:1,
            //启用分页,默认是客户端分页
            pagination:true,
            //启用服务器端分页
            sidePagination:'server',
            //设置true将禁止多选
            singleSelect:false,
            queryParams:function(params){
                var temp={
                    limit:params.limit,
                    offset:params.offset,
                    rname:$("#roleName").val()
                }
                return temp;
            },
            columns:[
                {
                    checkbox:true
                },
                {
                    field:'id',
                    title:'编号'
                },
                {
                    field:'rname',
                    title:'角色',
                },
                {
                    title:'操作',
                    formatter:function(value,row,index){
                        return "<button class='btn btn-info' onclick='toPer("+row.id+")' >分配权限</button>&nbsp;&nbsp;" +
                            "<button class='btn btn-info' onclick='toUpdate("+index+")'>修改</button>"
                    }
                }
            ]
        })
    }
    $(function(){
        table();
        formValidator();
    })
</script>
<script>
    var nodeCheckedSilent = false;
    function nodeChecked(event, node) {
        if (nodeCheckedSilent) {
            return;
        }
        nodeCheckedSilent = true;
        checkAllParent(node);
        checkAllSon(node);
        nodeCheckedSilent = false;
    }
    var nodeUncheckedSilent = false;

    function nodeUnchecked(event, node) {
        if (nodeUncheckedSilent)
            return;
        nodeUncheckedSilent = true;
        uncheckAllParent(node);
        uncheckAllSon(node);
        nodeUncheckedSilent = false;
    }

    //选中全部父节点
    function checkAllParent(node) {
        $('#searchTree').treeview('checkNode', node.nodeId, {
            silent: true
        });
        var parentNode = $('#searchTree').treeview('getParent', node.nodeId);
        if (!("nodeId" in parentNode)) {
            return;
        } else {
            checkAllParent(parentNode);
        }
    }
    //取消全部父节点
    function uncheckAllParent(node) {
        $('#searchTree').treeview('uncheckNode', node.nodeId, {
            silent: true
        });
        var siblings = $('#searchTree').treeview('getSiblings', node.nodeId);
        var parentNode = $('#searchTree').treeview('getParent', node.nodeId);
        if (!("nodeId" in parentNode)) {
            return;
        }
        var isAllUnchecked = true; //是否全部没选中
        for (var i in siblings) {
            if (siblings[i].state.checked) {
                isAllUnchecked = false;
                break;
            }
        }
        if (isAllUnchecked) {
            uncheckAllParent(parentNode);
        }
    }
    //级联选中所有子节点
    function checkAllSon(node) {
        $('#searchTree').treeview('checkNode', node.nodeId, {
            silent: true
        });
        if (node.nodes != null && node.nodes.length > 0) {
            for (var i in node.nodes) {
                checkAllSon(node.nodes[i]);
            }
        }
    }
    //级联取消所有子节点
    function uncheckAllSon(node) {
        $('#searchTree').treeview('uncheckNode', node.nodeId, {
            silent: true
        });
        if (node.nodes != null && node.nodes.length > 0) {
            for (var i in node.nodes) {
                uncheckAllSon(node.nodes[i]);
            }
        }
    }
</script>
</html>
